<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"llmysnow.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="介绍new、Object.create、instanceof、forEach、call、bind、promise">
<meta property="og:type" content="article">
<meta property="og:title" content="实现JS一些重要的API">
<meta property="og:url" content="http://llmysnow.top/posts/e8c036a5/index.html">
<meta property="og:site_name" content="奇幻的梦之旅">
<meta property="og:description" content="介绍new、Object.create、instanceof、forEach、call、bind、promise">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/20210910105320.png">
<meta property="article:published_time" content="2021-08-27T09:04:12.000Z">
<meta property="article:modified_time" content="2022-04-23T11:39:46.587Z">
<meta property="article:author" content="LiLyn">
<meta property="article:tag" content="instanceof">
<meta property="article:tag" content="方法实现">
<meta property="article:tag" content="new">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/20210910105320.png">

<link rel="canonical" href="http://llmysnow.top/posts/e8c036a5/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>实现JS一些重要的API | 奇幻的梦之旅</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="奇幻的梦之旅" type="application/atom+xml">
</head>
<!--即时预加载技术，在用户点击之前预先加载页面-->
<script src="https://cdn.jsdelivr.net/gh/TRHX/CDN-for-itrhx.com@2.0.2/js/instantclick-1.2.2.js" type="module"></script>
<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	  <!--<a target="_blank" rel="noopener" href="https://github.com/llwodexue" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>-->
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">奇幻的梦之旅</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">http://llmysnow.top/</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://llmysnow.top/posts/e8c036a5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/logo.jpg">
      <meta itemprop="name" content="LiLyn">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="奇幻的梦之旅">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          实现JS一些重要的API
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-08-27 17:04:12" itemprop="dateCreated datePublished" datetime="2021-08-27T17:04:12+08:00">2021-08-27</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>12k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>11 分钟</span>
            </span>
            <div class="post-description">介绍new、Object.create、instanceof、forEach、call、bind、promise</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="实现-new"><a href="#实现-new" class="headerlink" title="实现 new"></a>实现 new</h2><p>new 原理：</p>
<ol>
<li><p>创建Ctor的一个实例对象</p>
<p><code>实例.__proto__ = Ctor.prototype</code></p>
</li>
<li><p>把构造函数当做普通函数执行（让方法中的 this -&gt; 实例对象）</p>
</li>
<li><p>确认方法的返回值（如果没有返回值或者返回的是原始值，我们让其默认返回实例对象即可）</p>
</li>
</ol>
<p>需要考虑的点：</p>
<ul>
<li><p>Symbol、BigInt 不能被 new</p>
<p>我们知道 instanceof 是不能检测基本数据类型的 <code>Symbol() instanceof Symbol</code> 是 false。不过可以利用 call 方法来强迫装箱：当然这个也是 Function 和 Object 的实例</p>
<p>注意：使用 <code>Object.prototype.toString.call(f)</code> 也是 symbol，因为会先去找 <code>Symbol.toStringTag</code> 这个属性（返回的是 <code>&#39;[object Symbol]&#39;</code>），所以需要结合 typeof 来区分（进行了装箱操作把基本数据类型转换为对应的引用数据类型）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> f = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="built_in">this</span> &#125;.call(<span class="built_in">Symbol</span>(<span class="string">&#x27;&#x27;</span>))</span><br><span class="line">f <span class="keyword">instanceof</span> <span class="built_in">Symbol</span> <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Object</span>.prototype.toString.call(f) <span class="comment">// &#x27;[object Symbol]&#x27;</span></span><br><span class="line"><span class="keyword">typeof</span> f <span class="comment">// &#x27;object&#x27;</span></span><br></pre></td></tr></table></figure>

<p>生成器函数不需要基于 new 执行，就可以创造函数实例。其实相当于内部做了 <code>f.__proto__ = fn.prototype</code> 的处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">fn</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"><span class="keyword">let</span> f = fn()</span><br><span class="line">f <span class="keyword">instanceof</span> fn <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>箭头函数不能被 new</p>
<p>箭头函数没有 this，this 继承的是外层代码块的 this（也不能用 call 方法改变 this）</p>
<p>箭头函数不能使用 arguments，不过可以使用 rest 运算符</p>
<p>箭头函数不能使用 yield，箭头函数不能用作 Generator 函数</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">Ctor -&gt; constructor缩写（构造函数）</span></span><br><span class="line"><span class="comment">params -&gt; 后期给Ctor传递的所有实参信息</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">_new</span>(<span class="params">Ctor, ...params</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> obj,</span><br><span class="line">    result,</span><br><span class="line">    proto = Ctor.prototype</span><br><span class="line">  <span class="comment">// 校验规则</span></span><br><span class="line">  <span class="keyword">if</span> (Ctor === <span class="built_in">Symbol</span> || Ctor === BigInt || <span class="keyword">typeof</span> Ctor !== <span class="string">&#x27;function&#x27;</span> || !proto)</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">`<span class="subst">$&#123;Ctor&#125;</span> is not a constructor`</span>)</span><br><span class="line">  obj = <span class="built_in">Object</span>.create(Ctor.prototype)</span><br><span class="line">  result = Ctor.call(obj, ...params)</span><br><span class="line">  <span class="keyword">if</span> (<span class="regexp">/^(object|function)$/</span>.test(<span class="keyword">typeof</span> result)) <span class="keyword">return</span> result</span><br><span class="line">  <span class="keyword">return</span> obj</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.name = name</span><br><span class="line">&#125;</span><br><span class="line">Dog.prototype.bark = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;wangwang&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> bear = _new(Dog, <span class="string">&#x27;比尔&#x27;</span>)</span><br><span class="line">bear.bark() <span class="comment">// wangwang</span></span><br><span class="line"><span class="built_in">console</span>.log(bear <span class="keyword">instanceof</span> Dog) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<h2 id="实现-Object-create"><a href="#实现-Object-create" class="headerlink" title="实现 Object.create"></a>实现 Object.create</h2><p><code>Object.create([obj])</code>：创建一个空对象，并让 <code>空对象.__proto__</code> 指向 <code>[obj]</code></p>
<p>需要考虑的点：</p>
<ul>
<li><code>[obj]</code> 可以是一个对象或者是 null，但不能是其他的值</li>
<li><code>Object.create(null)</code> 创建一个不具备 <code>__proto__</code> 属性的对象（不是任何类的实例）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>.create = <span class="function"><span class="keyword">function</span> <span class="title">create</span>(<span class="params">prototype</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (prototype !== <span class="literal">null</span> || <span class="keyword">typeof</span> prototype !== <span class="string">&#x27;object&#x27;</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&#x27;Object prototype may only be&#x27;</span>)</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">Proxy</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">  <span class="built_in">Proxy</span>.prototype = prototype</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Proxy</span>()</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 如果传null是无法删除 obj.__proto__ 的</span></span><br></pre></td></tr></table></figure>

<h2 id="实现-instanceof"><a href="#实现-instanceof" class="headerlink" title="实现 instanceof"></a>实现 instanceof</h2><p>原理：查找 <code>[构造函数][Symbol.hasInstance](实例)</code> </p>
<ul>
<li>如果存在这个属性方法，则方法执行返回的值就是最后检测的结果</li>
<li>如果不存在这个属性方法，则会查找当前实例的原型链（一直找到 Object.prototype 为止），如果查找中，找到某个原型等于构造函数的原型，则返回true，反之false</li>
</ul>
<p><strong>注意：</strong> 基于 ES6 设置静态私有属性 <code>static [Symbol.hasInstance](value) &#123; return true &#125;</code> 是有效的</p>
<p>获取原型链需要考虑的点：</p>
<ul>
<li><code>Object.getPrototypeOf()</code> 不能获取 <code>null/undefined</code> 的原型</li>
</ul>
<p>instanceof 需要考虑的点：</p>
<ul>
<li>检测的所属类型（instanceof 右侧的所属类型）不能是箭头函数及非函数（基本数据类型的值、<code>&#123;&#125;</code> …）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">instance_of</span>(<span class="params">obj, Ctor</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 数据格式准确性校验</span></span><br><span class="line">  <span class="keyword">if</span> (Ctor == <span class="literal">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&quot;Right-hand side of &#x27;instanceof&#x27; is not callable&quot;</span>)</span><br><span class="line">  <span class="keyword">if</span> (!Ctor.prototype) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&quot;Function has non-object prototype &#x27;undefined&#x27; in instanceof check&quot;</span>)</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> Ctor !== <span class="string">&#x27;function&#x27;</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&quot;Right-hand side of &#x27;instanceof&#x27; is not callable&quot;</span>)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 原始值类型直接忽略</span></span><br><span class="line">  <span class="keyword">if</span> (obj === <span class="literal">null</span>) <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">  <span class="keyword">if</span> (!<span class="regexp">/^(object|function)$/</span>.test(<span class="keyword">typeof</span> obj)) <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 先检测是否有Symbol.hasInstance这个属性</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> Ctor[<span class="built_in">Symbol</span>.hasInstance] === <span class="string">&#x27;function&#x27;</span>) <span class="keyword">return</span> Ctor[<span class="built_in">Symbol</span>.hasInstance](obj)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 最后才会按照原型链进行处理</span></span><br><span class="line">  <span class="keyword">let</span> prototype = <span class="built_in">Object</span>.getPrototypeOf(obj)</span><br><span class="line">  <span class="keyword">while</span> (prototype) &#123;</span><br><span class="line">    <span class="keyword">if</span> (prototype === Ctor.prototype) <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    prototype = <span class="built_in">Object</span>.getPrototypeOf(prototype)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(instance_of([<span class="number">12</span>, <span class="number">23</span>], <span class="built_in">Array</span>)) <span class="comment">// true</span></span><br><span class="line"><span class="comment">// console.log(instance_of(null, null))</span></span><br><span class="line"><span class="comment">// console.log(instance_of(null, () =&gt; &#123;&#125;))</span></span><br><span class="line"><span class="comment">// console.log(instance_of(null, &#123;&#125;))</span></span><br></pre></td></tr></table></figure>

<h2 id="实现-forEach-方法（支持对象遍历）"><a href="#实现-forEach-方法（支持对象遍历）" class="headerlink" title="实现 forEach 方法（支持对象遍历）"></a>实现 forEach 方法（支持对象遍历）</h2><p>需要考虑的点：</p>
<ul>
<li>Symbol 无法用 <code>for...in...</code> 遍历的，可以使用 <code>Object.getOwnPropertySymbols()</code> 获取，之后结合 for 循环或 <code>Object.keys()</code> 使用即可</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">each</span>(<span class="params">obj, callback</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> keys = <span class="built_in">Object</span>.keys(obj),</span><br><span class="line">    key = <span class="literal">null</span>,</span><br><span class="line">    value = <span class="literal">null</span>,</span><br><span class="line">    i = <span class="number">0</span>,</span><br><span class="line">    len = <span class="number">0</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">Symbol</span> !== <span class="string">&#x27;undefined&#x27;</span>) &#123;</span><br><span class="line">    <span class="comment">// 支持Symbol</span></span><br><span class="line">    keys = keys.concat(<span class="built_in">Object</span>.getOwnPropertySymbols(obj))</span><br><span class="line">  &#125;</span><br><span class="line">  len = keys.length</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> callback !== <span class="string">&#x27;function&#x27;</span>) callback = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">  <span class="keyword">for</span> (; i &lt; len; i++) &#123;</span><br><span class="line">    key = keys[i]</span><br><span class="line">    value = obj[key]</span><br><span class="line">    callback(value, key)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其它常用数组方法的封装可以看我这篇文章：<a target="_blank" rel="noopener" href="https://editor.csdn.net/md/?articleId=111084399">JS 常用数组方法封装（包含splice）</a></p>
<h2 id="实现-call-bind"><a href="#实现-call-bind" class="headerlink" title="实现 call bind"></a>实现 call bind</h2><p>需要考虑的点：</p>
<ul>
<li><p>临时设置的属性，不能和原始对象冲突，所以属性采用唯一值处理</p>
<p>使用 <code>Symbol</code> 或 生成随机字符串 <code>Math.random() * new Date()</code></p>
</li>
<li><p>如果 context 不是对象（基本数据类型的值），需要将其处理成对象。如果 context 是 null 则需要单独处理</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">call</span>(<span class="params">context, ...params</span>) </span>&#123;</span><br><span class="line">  <span class="comment">/*</span></span><br><span class="line"><span class="comment">  this -&gt; 要执行的函数</span></span><br><span class="line"><span class="comment">  context -&gt; 要改变函数中this的指向</span></span><br><span class="line"><span class="comment">  params -&gt; 未来要传递给函数func的实参信息</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  context == <span class="literal">null</span> ? (context = <span class="built_in">window</span>) : <span class="literal">null</span></span><br><span class="line">  <span class="keyword">if</span> (!<span class="regexp">/^(object|function)$/</span>.test(<span class="keyword">typeof</span> context)) context = <span class="built_in">Object</span>(context)</span><br><span class="line">  <span class="keyword">let</span> self = <span class="built_in">this</span>,</span><br><span class="line">    key = <span class="built_in">Symbol</span>(<span class="string">&#x27;KEY&#x27;</span>),</span><br><span class="line">    result</span><br><span class="line">  context[key] = self</span><br><span class="line">  result = context[key](...params)</span><br><span class="line">  <span class="keyword">delete</span> context[key]</span><br><span class="line">  <span class="keyword">return</span> result</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">Function</span>.prototype._call = call</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj = &#123; <span class="attr">name</span>: <span class="string">&#x27;Bird&#x27;</span> &#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.total = x + y</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> res = func._call(obj, <span class="number">1</span>, <span class="number">2</span>) <span class="comment">// &#123;name:&#x27;Bird&#x27;, total:3&#125;</span></span><br></pre></td></tr></table></figure>

<p>bind 不是立即把函数执行，只是预先把 this 和后期需要传递的参数存储起来（柯理化函数）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">context, ...params</span>) </span>&#123;</span><br><span class="line">  <span class="comment">/*</span></span><br><span class="line"><span class="comment">  this -&gt; func</span></span><br><span class="line"><span class="comment">  context -&gt; obj</span></span><br><span class="line"><span class="comment">  params -&gt; [100,200]</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  context == <span class="literal">null</span> ? (context = <span class="built_in">window</span>) : <span class="literal">null</span></span><br><span class="line">  <span class="keyword">if</span> (!<span class="regexp">/^(object|function)$/</span>.test(<span class="keyword">typeof</span> context)) context = <span class="built_in">Object</span>(context)</span><br><span class="line">  <span class="keyword">let</span> self = <span class="built_in">this</span>,</span><br><span class="line">    key = <span class="built_in">Symbol</span>(<span class="string">&#x27;KEY&#x27;</span>),</span><br><span class="line">    result</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">proxy</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// args -&gt; 事件触发传递的信息，例如：ev</span></span><br><span class="line">    params = params.concat(args)</span><br><span class="line">    context[key] = self</span><br><span class="line">    result = context[key](...params)</span><br><span class="line">    <span class="keyword">delete</span> context[key]</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">Function</span>.prototype._bind = bind</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj = &#123; <span class="attr">name</span>: <span class="string">&#x27;Jhon&#x27;</span> &#125;</span><br><span class="line"><span class="built_in">document</span>.body.onclick = func._bind(obj, <span class="number">1</span>, <span class="number">2</span>)</span><br></pre></td></tr></table></figure>

<h2 id="实现-Promise"><a href="#实现-Promise" class="headerlink" title="实现 Promise"></a>实现 Promise</h2><p>先看一下 Promise 具有的方法：</p>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/20210910105320.png"></p>
<p>Promise 原理：</p>
<ol>
<li><p>首先会给当前实例增加状态（默认是 pending 等待态）和两个事件池 成功的事件池和失败的事件池（用来存放 then 中还不知道实例状态的事件）</p>
</li>
<li><p>其次最重要的就是 Promise 内部传递的 executor 函数，此函数会立即执行并会传递两个回调函数 resolve 和 reject，当执行任何一个回调函数时，都会做两件事情：<strong>更改状态、发布对应事件池的状态方法</strong> </p>
<p>注意：更改完状态就不能再更改了（是 pending 才会改状态）；执行回调函数时如果基于 then 存储过方法，依次通知对应状态的事件池方法执行，且执行是异步的微任务</p>
</li>
<li><p>new Promise 会创造实例，实例可以调用其所属类原型的方法，之后重构了一下 Promise 构造函数原型上的方法</p>
</li>
<li><p>then 方法返回一个全新的 Promise 实例，有两种情况：</p>
<ul>
<li>如果已经知道对应实例的状态，则创建一个异步的微任务，后期执行对应的 onFulfilled/onRejected</li>
<li>如果此时还不知道实例状态，就先把 onFulfilled/onRejected 存储起来，后期更改其状态之后，再通知方法执行即可，也是异步微任务</li>
</ul>
<p>注意：返回新的 Promise 实例不能和执行结果是同一个 <code>let p2 = p1.then(() =&gt; p2)</code> </p>
<p>如何验证返回的是否是一个新的 Promise 实例：类型是 object 或 function 且它得具有 then 方法（是一个函数）。如果返回的不是 Promise 实例，且执行没有报错，则返回一个成功的 Promise 实例</p>
</li>
<li><p>如果 then 中的某个回调函数（resolve、reject）不设置，其默认具备穿透性，顺延到下一个 then 中的同状态的方法上</p>
<p>如果没有传 onFulfilled 或 onRejected，就给对应的默认传递 resolve 或 reject 即可</p>
</li>
<li><p>catch 相当于调用 then，第一个参数不写，第二个参数传递错误原因</p>
</li>
<li><p>all 传入的必须是一个数组，如果数组中某一项不是 Promise 实例，需要把它转换为成功的 Promise 实例。之后把每一项依次执行，只要有一项失败返回就是失败的，必须全部成功才是成功</p>
<p>注意：返回结果的顺序跟传入的顺序一致（不能使用 push，因为不能确定谁先到，需要使用索引）</p>
</li>
</ol>
<p>需要注意的点：</p>
<ul>
<li>Promise 是一个构造函数，需要 new 执行</li>
<li>Promise 参数必须是一个函数</li>
<li>Promise then 里的方法实际上是异步的微任务，可以基于 queueMicrotask 去创造异步的微任务（兼容性差）；这里采用基于定时器创造一个异步的宏任务，来模拟微任务 </li>
</ul>
<p>ES6 方法实现 Promise，可以参考我另外一篇文章 <a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_38689395/article/details/114014869">手撕 Promise（内附then链实现）</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br></pre></td><td class="code"><pre><span class="line">;(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">Promise</span>(<span class="params">executor</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> self = <span class="built_in">this</span>,</span><br><span class="line">      change</span><br><span class="line">    <span class="comment">// 必须new执行</span></span><br><span class="line">    <span class="keyword">if</span> (!(self <span class="keyword">instanceof</span> <span class="built_in">Promise</span>)) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&#x27;undefined is not a promise&#x27;</span>)</span><br><span class="line">    <span class="comment">// executor必须是一个函数</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> executor !== <span class="string">&#x27;function&#x27;</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&#x27;Promise resolver &#x27;</span> + executor + <span class="string">&#x27; is not a function&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 实例具备的属性，状态和结果</span></span><br><span class="line">    self.state = <span class="string">&#x27;pending&#x27;</span></span><br><span class="line">    self.result = <span class="literal">undefined</span></span><br><span class="line">    self.onFulfilledCallbacks = []</span><br><span class="line">    self.onRejectedCallbacks = []</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 修改实例的状态</span></span><br><span class="line">    change = <span class="function"><span class="keyword">function</span> <span class="title">change</span>(<span class="params">state, result</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (self.state !== <span class="string">&#x27;pending&#x27;</span>) <span class="keyword">return</span></span><br><span class="line">      self.state = state</span><br><span class="line">      self.result = result</span><br><span class="line">      <span class="comment">// 创建异步微任务，通知集合中存储的方法执行（前提：集合中有东西才执行）</span></span><br><span class="line">      <span class="keyword">var</span> callbacks = state === <span class="string">&#x27;fulfilled&#x27;</span> ? self.onFulfilledCallbacks : self.onRejectedCallbacks,</span><br><span class="line">        i = <span class="number">0</span>,</span><br><span class="line">        len = callbacks.length,</span><br><span class="line">        callback</span><br><span class="line">      <span class="keyword">if</span> (callbacks.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">          <span class="keyword">for</span> (; i &lt; len; i++) &#123;</span><br><span class="line">            callback = callbacks[i]</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">typeof</span> callback === <span class="string">&#x27;function&#x27;</span>) callback(result)</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;, <span class="number">0</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// new Promise的时候会立即执行executor函数</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      executor(</span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">resolve</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">          change(<span class="string">&#x27;fulfilled&#x27;</span>, result)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">reject</span>(<span class="params">reason</span>) </span>&#123;</span><br><span class="line">          change(<span class="string">&#x27;rejected&#x27;</span>, reason)</span><br><span class="line">        &#125;</span><br><span class="line">      )</span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">      <span class="comment">// 执行executor报错，实例也是失败的状态</span></span><br><span class="line">      change(<span class="string">&#x27;rejected&#x27;</span>, error)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 验证是否为Promise</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">isPromise</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (x == <span class="literal">null</span>) <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="regexp">/^(object|function)$/i</span>.test(<span class="keyword">typeof</span> x)) &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">typeof</span> x.then === <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 处理onFulfilled/onRejected方法执行返回结果的处理</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">handle</span>(<span class="params">promiseNew, x, resolve, reject</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (x === promiseNew) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">&#x27;TypeError: Chaining cycle detected for promise #&lt;Promise&gt;&#x27;</span>)</span><br><span class="line">    <span class="keyword">if</span> (isPromise(x)) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        x.then(resolve, reject)</span><br><span class="line">      &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">        reject(err)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 返回不是promise实例，而且执行没有报错，则promiseNew一定是成功的，x是它的结果</span></span><br><span class="line">    resolve(x)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">Promise</span>.prototype = &#123;</span><br><span class="line">    <span class="title">constructor</span>: <span class="title">Promise</span>,</span><br><span class="line">    <span class="title">self</span>: <span class="title">true</span>,</span><br><span class="line">    <span class="title">then</span>: <span class="title">function</span> (<span class="params">onFulfilled, onRejected</span>) &#123;</span><br><span class="line">      <span class="keyword">var</span> self = <span class="built_in">this</span>,</span><br><span class="line">        promiseNew,</span><br><span class="line">        x</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">typeof</span> onFulfilled !== <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">        onFulfilled = <span class="function"><span class="keyword">function</span> <span class="title">onFulfilled</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> result</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">typeof</span> onRejected !== <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">        onRejected = <span class="function"><span class="keyword">function</span> <span class="title">onRejected</span>(<span class="params">reason</span>) </span>&#123;</span><br><span class="line">          <span class="keyword">throw</span> reason</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      promiseNew = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// resolve reject可以设置返回的@TP（新promise实例是成功还是失败以及结果等）</span></span><br><span class="line">        <span class="comment">// 但是执行哪个方法，由监听onFulfilled/onRejected方法报错以及返回值来决定</span></span><br><span class="line">        <span class="keyword">switch</span> (self.state) &#123;</span><br><span class="line">          <span class="keyword">case</span> <span class="string">&#x27;fulfilled&#x27;</span>:</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">              <span class="keyword">try</span> &#123;</span><br><span class="line">                x = onFulfilled(self.result)</span><br><span class="line">                handle(promiseNew, x, resolve, reject)</span><br><span class="line">              &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                reject(err)</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;, <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">          <span class="keyword">case</span> <span class="string">&#x27;rejected&#x27;</span>:</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">              <span class="keyword">try</span> &#123;</span><br><span class="line">                x = onRejected(self.result)</span><br><span class="line">                handle(promiseNew, x, resolve, reject)</span><br><span class="line">              &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                reject(err)</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;, <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">          <span class="keyword">default</span>:</span><br><span class="line">            self.onFulfilledCallbacks.push(<span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span><br><span class="line">              <span class="keyword">try</span> &#123;</span><br><span class="line">                x = onFulfilled(result)</span><br><span class="line">                handle(promiseNew, x, resolve, reject)</span><br><span class="line">              &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                reject(err)</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">            self.onRejectedCallbacks.push(<span class="function"><span class="keyword">function</span> (<span class="params">reason</span>) </span>&#123;</span><br><span class="line">              <span class="keyword">try</span> &#123;</span><br><span class="line">                x = onRejected(reason)</span><br><span class="line">                handle(promiseNew, x, resolve, reject)</span><br><span class="line">              &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                reject(err)</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">return</span> promiseNew</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">catch</span>: <span class="function"><span class="keyword">function</span> (<span class="params">onRejected</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">this</span>.then(<span class="literal">null</span>, onRejected)</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">Symbol</span> !== <span class="string">&#x27;undefined&#x27;</span>) <span class="built_in">Promise</span>.prototype[<span class="built_in">Symbol</span>.toStringTag] = <span class="string">&#x27;Promise&#x27;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 普通对象：私有静态方法</span></span><br><span class="line">  <span class="built_in">Promise</span>.all = <span class="function"><span class="keyword">function</span> <span class="title">all</span>(<span class="params">promises</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> promiseNew,</span><br><span class="line">      results = [],</span><br><span class="line">      n = <span class="number">0</span></span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">Array</span>.isArray(promises)) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(promises + <span class="string">&#x27; is not iterable&#x27;</span>)</span><br><span class="line">    <span class="comment">// 控制集合中的每一项都是Promise实例</span></span><br><span class="line">    promises = promises.map(<span class="function"><span class="keyword">function</span> (<span class="params">promise</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (!isPromise(promise)) <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(promise)</span><br><span class="line">      <span class="keyword">return</span> promise</span><br><span class="line">    &#125;)</span><br><span class="line">    promiseNew = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">      promises.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">promise, index</span>) </span>&#123;</span><br><span class="line">        promise</span><br><span class="line">          .then(<span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span><br><span class="line">            <span class="comment">// result存储的是当前迭代这一项的成功结果</span></span><br><span class="line">            n++</span><br><span class="line">            results[index] = result</span><br><span class="line">            <span class="comment">// 都处理成功</span></span><br><span class="line">            <span class="keyword">if</span> (n &gt;= promises.length) resolve(results)</span><br><span class="line">          &#125;)</span><br><span class="line">          .catch(<span class="function"><span class="keyword">function</span> (<span class="params">reason</span>) </span>&#123;</span><br><span class="line">            <span class="comment">// 只要有一项失败，整体就是失败</span></span><br><span class="line">            reject(reason)</span><br><span class="line">          &#125;)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> promiseNew</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">Promise</span>.resolve = <span class="function"><span class="keyword">function</span> <span class="title">resolve</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">      resolve(result)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">Promise</span>.reject = <span class="function"><span class="keyword">function</span> <span class="title">reject</span>(<span class="params">reason</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">_, reject</span>) </span>&#123;</span><br><span class="line">      reject(reason)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/* 暴露API */</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">window</span> !== <span class="string">&#x27;undefined&#x27;</span>) <span class="built_in">window</span>.Promise = <span class="built_in">Promise</span></span><br><span class="line">  <span class="comment">// if (typeof module === &#x27;object&#x27; &amp;&amp; typeof module.exports === &#x27;object&#x27;) module.exports = Promise</span></span><br><span class="line">&#125;)()</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">Math</span>.random() &lt; <span class="number">0.6</span> ? resolve(<span class="string">&#x27;OK&#x27;</span>) : reject(<span class="string">&#x27;NO&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// try catch 一般情况下是无法捕捉到异步任务执行报错信息</span></span><br><span class="line"><span class="keyword">let</span> p2 = p1.then(<span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;成功&#x27;</span>, result)</span><br><span class="line">  <span class="keyword">return</span> <span class="number">200</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> p3 = p2.then(</span><br><span class="line">  <span class="function"><span class="keyword">function</span> (<span class="params">result</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;成功&#x27;</span>, result)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="function"><span class="keyword">function</span> (<span class="params">reason</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;失败&#x27;</span>, reason)</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> p4 = <span class="built_in">Promise</span>.resolve(<span class="number">10</span>)</span><br><span class="line"><span class="keyword">let</span> p5 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="number">20</span>)</span><br><span class="line">  &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">let</span> p6 = <span class="number">30</span></span><br><span class="line"><span class="built_in">Promise</span>.all([p4, p5, p6])</span><br><span class="line">  .then(<span class="function"><span class="params">results</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;成功&#x27;</span>, results)</span><br><span class="line">  &#125;)</span><br><span class="line">  .catch(<span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;失败&#x27;</span>, reason)</span><br><span class="line">  &#125;)</span><br></pre></td></tr></table></figure>

<h2 id="接下来参考"><a href="#接下来参考" class="headerlink" title="接下来参考"></a>接下来参考</h2><p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903924520992782">关于JS中一些重要的api实现, 巩固你的原生JS功底</a></p>

    </div>

    
    
    

	<div>
		  
			
<div class="my_post_copyright clearfix">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <article class="box-left">
    <img src="https://gitee.com/lilyn/pic/raw/master/logo.jpg">
  </article>
  <article class="box-right">
    <p><span>本文标题:</span><a href="/posts/e8c036a5/">实现JS一些重要的API</a></p>
    <p><span>文章作者:</span><a href="/" title="访问 LiLyn 的个人博客">LiLyn</a></p>
    <p><span>原始链接:</span><a href="/posts/e8c036a5/" title="实现JS一些重要的API">http://llmysnow.top/posts/e8c036a5/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://llmysnow.top/posts/e8c036a5/"  aria-label="复制成功！"></i></span>
  </p>
    <p><span>许可协议:</span>转载请保留原文链接及作者。</p>  
  </article>
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

		  
	</div>

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/instanceof/" rel="tag"><i class="fa fa-tag"></i> instanceof</a>
              <a href="/tags/%E6%96%B9%E6%B3%95%E5%AE%9E%E7%8E%B0/" rel="tag"><i class="fa fa-tag"></i> 方法实现</a>
              <a href="/tags/new/" rel="tag"><i class="fa fa-tag"></i> new</a>
          </div>
		 
		<!--post-tags 彩色标签-->
		<script type="text/javascript">
		var tagsall=document.getElementsByClassName("post-tags")
		for (var i = tagsall.length - 1; i >= 0; i--){
			var tags=tagsall[i].getElementsByTagName("a");
			for (var j = tags.length - 1; j >= 0; j--) {
				var r=Math.floor(Math.random()*75+130);
				var g=Math.floor(Math.random()*75+100);
				var b=Math.floor(Math.random()*75+80);
				tags[j].style.background = "rgb("+r+","+g+","+b+")";
				tags[j].style.color = "#fff";
				tags[j].style.padding = "0 10px";
			}
		}                        
		</script>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/4317de95/" rel="prev" title="Webpack（优化和问题）">
      <i class="fa fa-chevron-left"></i> Webpack（优化和问题）
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/126e4b0f/" rel="next" title="Node 事件循环及多线程">
      Node 事件循环及多线程 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-new"><span class="nav-text">实现 new</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-Object-create"><span class="nav-text">实现 Object.create</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-instanceof"><span class="nav-text">实现 instanceof</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-forEach-%E6%96%B9%E6%B3%95%EF%BC%88%E6%94%AF%E6%8C%81%E5%AF%B9%E8%B1%A1%E9%81%8D%E5%8E%86%EF%BC%89"><span class="nav-text">实现 forEach 方法（支持对象遍历）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-call-bind"><span class="nav-text">实现 call bind</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0-Promise"><span class="nav-text">实现 Promise</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8E%A5%E4%B8%8B%E6%9D%A5%E5%8F%82%E8%80%83"><span class="nav-text">接下来参考</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="LiLyn"
      src="/images/logo.jpg">
  <p class="site-author-name" itemprop="name">LiLyn</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">70</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">162</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/llwodexue" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;llwodexue" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_38689395" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_38689395" rel="noopener" target="_blank"><i class="fas fa-copyright fa-fw"></i>CSDN</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://scx69.gitee.io/blogs/" title="https:&#x2F;&#x2F;scx69.gitee.io&#x2F;blogs&#x2F;" rel="noopener" target="_blank">花开满城</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://yixin-oss.gitee.io/daytoy/" title="http:&#x2F;&#x2F;yixin-oss.gitee.io&#x2F;daytoy&#x2F;" rel="noopener" target="_blank">daytoy</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LiLyn</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">463k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:01</span>
</div>

<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>-->

<!--
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>-->

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  <!-- 动态线条背景 -->
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  <!-- 页面点击小红心 -->
  <script type="text/javascript">
	!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);
  </script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>
</html>